package org.example.projecttwo.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.projecttwo.entity.user.User;
import org.example.projecttwo.mapper.user.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;


    /**
     * 根据用户ID加载用户详情
     * @param userId 用户ID
     * @return 用户详情
     * @throws UsernameNotFoundException 用户不存在
     */
    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        User user = userMapper.selectOne(
                new LambdaQueryWrapper<User>()
                        .eq(User::getId, Long.valueOf(userId))
        );
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 返回 Spring Security 的 UserDetails 实现
        return org.springframework.security.core.userdetails.User
                .builder()
                .username(user.getId().toString())
                .password(user.getPassword())
                .disabled(user.getStatus() != 0) // status=0 正常，否则禁用
                .authorities(user.getRoleCode()) // 如 ADMIN ,USER
                .build();
    }
}